package com.hk.service.quartz;

/**
 * 根据获得的开始和结束时间，自动更改其状态
 */

import com.hk.commons.Constant;
import com.hk.commons.HqlFilter;
import com.hk.commons.entity.Activity;
import com.hk.service.kyc.IActivity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Timestamp;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.springframework.beans.factory.annotation.Autowired;



public class ActivityStartStatusQuartz extends BaseQuartz {

	private Logger logger = LoggerFactory.getLogger(ActivityStartStatusQuartz.class);

	@Autowired
	private IActivity  actImpl;

	@Override
	public void start() {
		logger.info(" will  start to check activity status ");
		ExecutorService executor = Executors.newFixedThreadPool(1);
		Runnable task = new Runnable() {
			public void run() {
				logger.info(" start to check activity status ");
				startAct();
				endAct();
			}
		};
		executor.execute(task);
		executor.shutdown();
	}

	private void startAct() {
		HqlFilter hqlFilter = new HqlFilter();

		Long curTimeLong = System.currentTimeMillis();
		Timestamp curTime = new Timestamp(curTimeLong);

		//获取未设置售罄的产品
		hqlFilter.addSql(" where startStatus is not null  and  startTime is not null " +
				" and startTime < '" + curTime + "' and  ((startStatus = " + Constant.ACTIVITY_START_STATUS_NOSTART + ") "  + " or (startStatus = " + Constant.ACTIVITY_START_STATUS_YURE + ") )");

		logger.info("activity startAct sql ={}",hqlFilter.getWhereAndOrderHql());

		List<Activity> actList = actImpl.findByFilter(hqlFilter);
		if(actList != null) {
			logger.info("list size = {}" + actList.size());
		}else{
			logger.info("list size is null");
		}

		for(Activity act:actList){
			act.setStartStatus(Constant.ACTIVITY_START_STATUS_START);
			actImpl.update(act);
			logger.info("activity  will update the startStatus to start, act name={}", act.getName());
		}
	}

	private void endAct() {
		HqlFilter hqlFilter = new HqlFilter();

		Long curTimeLong = System.currentTimeMillis();
		Timestamp curTime = new Timestamp(curTimeLong);

		//获取未设置售罄的产品
		hqlFilter.addSql(" where startStatus is not null  and  endTime is not null and endTime < '" + curTime + "' and  startStatus = " + Constant.ACTIVITY_START_STATUS_START  );
		logger.info("activity endAct sql ={}",hqlFilter.getWhereAndOrderHql());

		List<Activity> actList = actImpl.findByFilter(hqlFilter);
		if(actList != null) {
			logger.info("list size = {}" + actList.size());
		}else{
			logger.info("list size is null");
		}

		for(Activity act:actList){
			act.setStartStatus(Constant.ACTIVITY_START_STATUS_END);
			actImpl.update(act);
			logger.info("activity  will update the startStatus to end, act name={}", act.getName());
		}
	}
}
